package cn.campsg.messageboard.controller.Admin;

import cn.campsg.messageboard.dao.MessageDaoImpl;
import cn.campsg.messageboard.dao.UserDao;
import cn.campsg.messageboard.model.Message;
import cn.campsg.messageboard.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@WebServlet("/admin/dashboard")
public class DashboardServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 权限校验
        if (request.getSession().getAttribute("admin") == null) {
            response.sendRedirect("admin_login.jsp");
            return;
        }

        try {
            // 获取消息列表
            MessageDaoImpl messageService = new MessageDaoImpl();
            List<Message> messages = messageService.getAllMessages();

            // 获取用户列表
            UserDao userDao = new UserDao();
            List<User> users = userDao.getAllUsers();

            // 设置请求属性 - 确保不为 null
            request.setAttribute("messages", messages != null ? messages : Collections.emptyList());
            request.setAttribute("users", users != null ? users : Collections.emptyList());

            // 转发到 JSP
            request.getRequestDispatcher("/admin_dashboard.jsp").forward(request, response);

        } catch (Exception e) {
            // 错误处理
            request.setAttribute("error", "加载数据时出错: " + e.getMessage());
            request.setAttribute("messages", Collections.emptyList());
            request.setAttribute("users", Collections.emptyList());
            request.getRequestDispatcher("/admin_dashboard.jsp").forward(request, response);
        }
    }
}